import React from 'react';
import AdvancedTable from 'components/advanced-table'
import financeAuditService from './finance-audit.service'
import { dealListTag, invoiceAmountChange, messages, queryCurrencyPrecision } from "share/common";
import { Popover } from "antd";
import moment from 'moment'
import selectorData from "share/selectorData";
import NumberRange from 'containers/financial-management/expense-view/component/number-range'
import CostCenterSearchForm from "components/template/cost-center-search-form/cost-center-search-form";
import expBagCode from './searchForm-components/expBagCode'
import openSlideFrame from "share/openSlideFrame";
import { labelIds } from 'containers/financial-management/expense-view/component/func-component';
import Department from 'components/template/department';
import {connect} from "react-redux";

class FinanceAuditExpense extends React.Component {

  state = {
    sort: ''
  };

  searchForm = [
    {
      id: 'formOIDs',
      component: 'MultiSelectorV2',
      label: messages('expense-14.key220')/*表单类型*/,
      props: {
        type: 'authority_form',
        params: { formType: 3004 },
        labelKey: 'formName',
        isShowSelectAll: true
      },
      parser: value => ({
        formOIDs: value ? value.map(item => item.formOID) : null
      })
    }, {
    id: 'submittedDate', label: messages('common.submit.date')/*提交日期*/,
    component: 'DateRangePicker',
    parser: value => ({
      startDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
      endDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'corpSupplierId', label: messages('expense-14.key502')/*供应商*/,
    component: 'Chooser',
    props: {
      type: 'vendor_account',
      labelKey: 'venNickname',
      valueKey: 'id',
      listExtraParams: {
        companyOid: this.props.company.companyOID
      },
      dataIndex: 'corpSupplierId'
    },
    parser: value => ({
      corpSupplierId: value ? value.map(item => item.id) : null
    })
  }, {
    id: 'searchCostCenterCommands', label: messages('expense-14.key221')/*成本中心*/,
    component: <CostCenterSearchForm title={messages('expense-14.key221')/*成本中心*/}/>,
    tagParser: value => messages('common.total.selected',{arg1: value.length})/*已选 {arg1} 条*/
  }, {
    id: 'departmentOids',
    label: messages('common.department')/*部门*/,
    component: <Department/>,
    parser: value => ({
      departmentOids: value ? value.map(item => item.departmentOID) : null
    }),
    tagParser: value => (value.map(item => item.title).join(','))
  }, {
    id: 'approvalDate', label: messages('expense-14.key222')/*审批日期*/,
    component: 'DateRangePicker',
    parser: value => ({
      approvalStartDate: value && value[0] ? moment(value[0]).format('YYYY-MM-DD 00:00:00') : null,
      approvalEndDate: value && value[1] ? moment(value[1]).format('YYYY-MM-DD 23:59:59') : null
    })
  }, {
    id: 'businessCode',
    component: 'Selector',
    label: messages('common.document.code')/*单号*/,
    props: {
      placeholder: messages('common.please.input')/*请输入*/ + messages('common.document.code')/*单号*/,
      type: 'business_code_expense',
      params: {
        status: this.props.status
      }
    }
  }, {
    id: 'applicantOID', label: messages('expense-14.key223')/*员工*/,
    component: 'Selector',
    props: {
      placeholder: messages('common.please.input')/*请输入*/ + messages('expense-14.key224')/*申请人姓名/工号*/,
      type: 'user',
      selectorItem: {
        ...selectorData['user'],
        url: `/api/user/documents/review/search`,
        label: record => (`${record.employeeID}-${record.fullName}${(record.status !== 1001 ?
            (`（${record.status === 1002 ?
                messages('expense-14.key225')/*待离职员工*/ :
                messages('expense-14.key226')/*离职员工*/}）`
            ) :
            ''
        )}`)
      }
    },
  }, {
    component: 'Chooser',
    id: 'selectCompanyOIDs',
    label: messages('request-4.key12')/*公司*/,
    props: {
      labelKey: 'name',
      valueKey: 'companyOID',
      type: 'permission_company',
      listExtraParams:{enabled: true}
    },
    parser: value => ({
      selectCompanyOIDs: value ? value.map(item => item.companyOID) : null
    }),
    JSONObjectFormatterParams: ['departmentName', 'companyOID']
  }, {
    id: 'totalAmount',
    label: messages('expense-14.key228')/*金额范围*/,
    component: <NumberRange/>,
    parser: value => ({
      minTotalAmount: value && value[0] ? value[0] : null,
      maxTotalAmount: value && value[1] ? value[1] : null
    }),
    tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
  }, {
    id: 'creditScore',
    label: messages('expense-14.key229')/*信用分范围*/,
    component: <NumberRange/>,
    parser: value => ({
      creditScoreFrom: value && value[0] ? value[0] : null,
      creditScoreTo: value && value[1] ? value[1] : null
    }),
    tagParser: value => value && (value[0] || value[1]) && `${value[0] === 0 ? value[0] : value[0] || ''} ~ ${value[1] === 0 ? value[1] : value[1] || ''}`
  }, labelIds(), {
    id: 'nodeOIDs',
    component: 'MultiSelectorV2',
    label: messages('expense-14.key230')/*节点名称*/,
    props: {
      type: 'billNodeName',
      params: { entityType: 1002, status: this.props.status || 'prending_audit', corporateFlag: true },
      labelKey: 'name',
      isShowSelectAll: true
    },
    parser: value => ({
      nodeOIDs: value && value.length ? value.map(item => item.key).join(',').split(',') : null
    })
  }];

  columns = [{
    title: messages('common.applicant')/*申请人*/, dataIndex: "applicantName", width: '10%'
  }, {
    title: messages('common.user.id')/*工号*/, dataIndex: "employeeID", width: '10%'
  }, {
    title: messages('common.submit.date')/*提交日期*/, dataIndex: "submittedDate", width: 120,
    render: date => new Date(date).format('yyyy-MM-dd'), sorter: true
  }, {
    title: messages('expense-14.key503')/*供应商名称*/, dataIndex: 'corpSupplierName',
    render: value => <Popover content={value}>{value}</Popover>
  }, {
    title: messages('expense-14.key231')/*单据类型*/, dataIndex: 'formName', width: '10%',
    render: formName => (
        <Popover content={formName}>
          {formName}
        </Popover>
      ),
    sorter: true
  }, {
    title: messages('common.document.code')/*单号*/ , dataIndex: 'childBusinessCode', width: '15%',
    render: (text, record) => {
      let showText = !record.parentBusinessCode && record.businessCode ||
        record.parentBusinessCode !== record.childBusinessCode && (record.parentBusinessCode + '-' + record.childBusinessCode) ||
        record.childBusinessCode;
      return (
        <Popover content={showText}>
          {showText}
        </Popover>
      )
    },
    sorter: true
  }, {
    title: messages('expense-14.key230')/*节点名称*/,
    dataIndex: 'nodeName',
    hide: true,
    render: value => value ? <Popover content={value} placement="topLeft">{value}</Popover> : ''
  }, {
    title: messages('common.currency')/*币种*/, dataIndex: "currencyCode", width: 72
  }, {
    title: messages('expense-14.key504')/*到票金额*/, dataIndex: 'totalAmount',  align: 'right',
    render: (totalAmount, record) => {
      let showText = invoiceAmountChange(record.reviewedFlag, totalAmount, record.currencyCode);
      return (<Popover content={showText}>
        {showText}
      </Popover>)
    }, width: '7%'
  }, {
    title: messages('expense-14.key505')/*支付金额*/, dataIndex: 'paymentTotalAmount', align: 'right',
    render: (value, record) => {
      let showText = invoiceAmountChange(record.reviewedFlag, value, record.currencyCode);
      return (<Popover content={showText}>
        {showText}
      </Popover>)
    },
    width: '7%'
  }, {
    title: messages('expense-14.key239')/*支付币种*/,
    dataIndex: 'baseCurrency',
    width: 100,
    render: (value, record) => record.currencyCode
  }, {
    title: messages('expense-14.key234')/*凭证编号*/, width: 120,
    dataIndex: "origDocumentSequence",
    render: value => {
      return <Popover content={value} placement="topLeft">{value}</Popover>
    }
  }];

  componentDidMount() {
    const { onRef } = this.props;
    onRef && onRef(this);
  }

  duePay = (value,currencyCode) => {
    let text = this.filterMoney(value,queryCurrencyPrecision(currencyCode));
    return (<Popover content={text}>{text}</Popover>)
  };

  service = (page, pageSize, searchParams) => {
    const { status } = this.props;
    const { sort } = this.state;
    let params = { status, ...searchParams, corporateFlag: true };
    return financeAuditService.getAuditCorporateList(page, pageSize, sort, params)
  };

  onChangeTable = (pagination, filters, sorter) => {
    const { sort } = this.state;
    let nextSort = '';
    if(sorter.order) {
      nextSort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    if(nextSort !== sort) {
      this.setState({ sort: nextSort }, this.advancedTableRef.getList);
    }
  };

  handleRowClick = record => {
    const { status } = this.props;
    openSlideFrame.openCorporateReportDetail({
      expenseReportOID: record.expenseReportOID,
      status: status,
      entry: 'audit',
      backType: 'history'
    }, {
      noPadding: true,
      afterClose: this.afterClose
    }, this);
  };

  afterClose = value => typeof value === 'boolean' && value && this.advancedTableRef.getList();

  render() {
    const { status } = this.props;
    return (
      <AdvancedTable
        index
        expandAll
        title={status === 'prending_audit' ? messages('expense-14.key506')/*【对公支付单】待审核*/ : messages('expense-14.key507')/*【对公支付单】已审核*/}
        searchForm={this.searchForm}
        columns={this.columns}
        service={this.service}
        onChange={this.onChangeTable}
        onRef={ref => this.advancedTableRef = ref}
        expandedRowRender={dealListTag}
        waterMark={true}
        rowKey={record => record.expenseReportOID}
        onRow={record => ({
          onClick: () => this.handleRowClick(record)
        })}
        pinnedList={['submittedDate', 'approvalDate', 'businessCode']}
        tableName={`finance-audit.corporate.${status}`}
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(FinanceAuditExpense)
